﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.Platform;
using NewRetail.Application.Components.Platform.Entity;
using NewRetail.Application.Core;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace NewRetail.Api.Controllers
{
    [NewRetailRoute("pos-member")]
    public class PosMemberController : BaseController<PosMember, PosMemberPagingDto>
    {
        private readonly IPosMemberService posMemberService;
        public PosMemberController(IPosMemberService posMemberService)
        {
            this.posMemberService = posMemberService;
        }

        protected override async Task<IQueryable<PosMember>> FilterQueryPaging(DbContext db, IQueryable<PosMember> query, PosMemberPagingDto dto)
        {
            var now = this.Clock.Now;
            if (dto.available)
            {
                query = query.Where(x => x.startDate <= now && x.endDate >= now);
            }
            query = query.WhereIf(!string.IsNullOrWhiteSpace(dto.warehouseId), x => x.sourceWarehouseID == dto.warehouseId);
            query = query.WhereIf(!string.IsNullOrWhiteSpace(dto.memberTypeId), x => x.memberTypeID == dto.memberTypeId);

            query = query.WhereIf(!string.IsNullOrWhiteSpace(dto.cardNo), x => x.No.Contains(dto.cardNo));
            query = query.WhereIf(!string.IsNullOrWhiteSpace(dto.name), x => x.memberName.Contains(dto.name));
            query = query.WhereIf(!string.IsNullOrWhiteSpace(dto.phone), x => x.memberTel.Contains(dto.phone));

            return await base.FilterQueryPaging(db, query, dto);
        }

        public override async Task<ResponseEntity<PagedResultDto<PosMember>>> QueryPaging([FromBody] PosMemberPagingDto dto)
        {
            var res = await base.QueryPaging(dto);

            if (res.Data?.Items?.Any() ?? false)
            {
                res.Data.Items = await this.posMemberService.AttachWarehouse(res.Data.Items.ToArray());
                res.Data.Items = await this.posMemberService.AttachMemberType(res.Data.Items.ToArray());
                res.Data.Items = await this.posMemberService.AttachCashier(res.Data.Items.ToArray());
            }

            return res;
        }

        protected override async Task<PosMember> BeforeInsertDataInitial(PosMember data)
        {
            if (string.IsNullOrWhiteSpace(data.No))
            {
                data.No = await this.NoGeneratorService.GenerateGeneralNoAsync("MB");
            }
            return await base.BeforeInsertDataInitial(data);
        }
    }
}
